package com.everflourish.yeah100.act.statistics;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.adapter.FragmentTeacherGradeAdapter;
import com.everflourish.yeah100.entity.statistics.ClassScoreInfo;
import com.everflourish.yeah100.entity.statistics.StudentScoreInfo;
import com.everflourish.yeah100.http.ExaminationRequest;
import com.everflourish.yeah100.ui.MyHScrollView;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.collections.GradeCollections;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/6.
 * 时间：2016/7/6
 */
public class FragmentTeacherGrade extends BaseFragment {

    private RecyclerView mRecycleList;
    public FragmentTeacherGradeAdapter mAdapter;
    private ExaminationRequest mRequest;
    public List<StudentScoreInfo> mList;
    private List<MyHScrollView> myHScrollViews;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    public SwipeRefreshLayout.OnRefreshListener mRefreshListener;
    private TextView mEmptyTv;
    private TeacherStatisticsActivity mActivity;
    private boolean isPrepared;  //  标志位，标志已经初始化完成。

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_teacher_grade, container, false);
        isPrepared = true;
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        initData();
        initFragment();
        configWidget();
        isPrepared = false;
    }

    private void initData() {
        mActivity = (TeacherStatisticsActivity) getActivity();
        mRequest = ExaminationRequest.getInstance();
        myHScrollViews = new ArrayList<MyHScrollView>();
        mList = new ArrayList<StudentScoreInfo>();
        mAdapter = new FragmentTeacherGradeAdapter(mContext, myHScrollViews, mList);
    }

    private void initFragment() {
        mRecycleList = (RecyclerView) getView().findViewById(R.id.statistics_teacher_rv);
        mSwipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.statistics_teacher_swipe);
        mEmptyTv = (TextView) getView().findViewById(R.id.statistics_t_grade_empty_tv);
        MyHScrollView myHScrollView = (MyHScrollView) getView().findViewById(
                R.id.statistics_t_title_mhv);
        myHScrollViews.add(myHScrollView);
        myHScrollView.setMyHScrollViews(myHScrollViews);
    }

    @SuppressWarnings("ResourceType")
    private void configWidget() {
        mRecycleList.setAdapter(mAdapter);
        mRecycleList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                studentGradeRequest();
            }
        };
        mSwipeRefreshLayout.setColorScheme(R.color.statistics_appbar_primary);
        mSwipeRefreshLayout.setOnRefreshListener(mRefreshListener);
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
            }
        });
        mRefreshListener.onRefresh();
    }

    /**
     * 获取学生成绩分析请求
     */
    private void studentGradeRequest() {
        JsonObjectRequest request = mRequest.tScoreListRequest(
                mActivity.mExamination.getId(), null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        scoreInfosListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mSwipeRefreshLayout.setRefreshing(false);
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取考生成绩失败");
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }

    /**
     * 获取学生成绩分析监听
     *
     * @param response
     */
    private void scoreInfosListener(JSONObject response) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.CLASS_SCORES);
                Gson gson = new Gson();
                Type type = new TypeToken<List<ClassScoreInfo>>() {
                }.getType();
                List<ClassScoreInfo> classScoreInfoList = gson.fromJson(
                        jsonArray.toString(), type);
                if (classScoreInfoList == null
                        || classScoreInfoList.size() == 0) {
                    // 获取学生成绩为空
//                    MyToast.showShort(mContext, "没有找到相关的学生成绩");
                    mEmptyTv.setVisibility(View.VISIBLE);
                    setList(classScoreInfoList);
                } else {
                    mEmptyTv.setVisibility(View.GONE);
                    setList(classScoreInfoList);
                    mAdapter.notifyDataSetChanged();
                }
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext,
                        R.string.examination_08041_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext,
                        R.string.examination_08042_000012E);
            } else if (resultCode
                    .equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext,
                        R.string.examination_08043_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext,
                        R.string.examination_080499_999999E);
            } else {
                MyToast.showShort(mContext, "获取考生成绩失败");
            }
        } catch (Exception e) {
            LogUtil.e("", e);
            MyToast.showShort(mContext, "获取考生成绩失败");
        } finally {
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            });
        }
    }

    /**
     * 将List<ClassScoreInfo> 转换为 List<StudentScoreInfo>
     *
     * @param classScoreInfos
     */
    private void setList(List<ClassScoreInfo> classScoreInfos) {
        mList.clear();
        for (ClassScoreInfo c : classScoreInfos) {
            if (c.getStudentScores() != null) {
                for (StudentScoreInfo s : c.getStudentScores()) {
                    s.setClassId(c.getClassId());
                    s.setClassName(c.getClassName());
                    mList.add(s);
                }
            }
        }
        studentNoSort();
    }

    /**
     * 根据学号升序或者降序
     */
    private void studentNoSort() {
        Collections.sort(mList, new GradeCollections(false,
                GradeCollections.COMPARE_STUDENT_NO));
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }
}